/**
 * 得到一个新的promise
 * 该promise的状态取决于promise的执行
 * 全成功就成功, 一个失败就失败
 * @param {iterator} iterator
 */
Promise.myAll = function (iterator) {
  return new Promise((resolve, reject) => {
    try {
      const results = [];
      let count = 0;
      let fulfilledCount = 0;
      for (const val of iterator) {
        count++;
        const innerCount = count;
        Promise.resolve(val).then((data) => {
          fulfilledCount++;
          results[innerCount - 1] = data;
          if (fulfilledCount === count) {
            console.log("全部完成了", fulfilledCount);
            resolve(results);
          }
        }, reject);
      }

      if (count === 0) {
        resolve(result);
      }
    } catch (error) {
      reject(error);
    }
    // console.log(count, fulfilledCount);
  });
};

Promise.myAll([
  new Promise((resolve, reject) => {
    setTimeout(() => {
      reject(1);
    }, 300);
  }),
  1,
  2,
])
  .then((data) => {
    console.log("data", data);
  })
  .catch((err) => {
    console.log(err);
  });
